package com.bw.service.order.impl;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.entity.Invoice.PiPayLog;
import com.bw.entity.craft.PiOrderItemMaterial;
import com.bw.entity.craft.PiOrderItemProcess;
import com.bw.entity.information.PiMaterial;
import com.bw.entity.information.PiProcess;
import com.bw.entity.order.PiOrder;
import com.bw.entity.user.TbUser;
import com.bw.mapper.order.PiOrderMapper;
import com.bw.req.OrderExp;
import com.bw.req.OrderItem;
import com.bw.resp.ResponseResult;
import com.bw.service.Invoice.IPiPayLogService;
import com.bw.service.craft.IPiOrderItemMaterialService;
import com.bw.service.craft.IPiOrderItemProcessService;
import com.bw.service.information.IPiMaterialService;
import com.bw.service.information.IPiProcessService;
import com.bw.service.order.IPiOrderService;
import com.bw.utils.aliPay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.entity.information.PiCustomer;
import com.bw.entity.order.PiOrder;
import com.bw.entity.order.PiOrderItem;
import com.bw.entity.order.PiOrderLog;
import com.bw.mapper.order.PiOrderMapper;
import com.bw.req.OrderAndItem;
import com.bw.service.information.IPiCustomerService;
import com.bw.service.information.IPiLinkmanService;
import com.bw.service.order.IPiOrderItemService;
import com.bw.service.order.IPiOrderLogService;
import com.bw.service.order.IPiOrderService;
import com.bw.service.user.ITbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-20
 */
@Service
public class PiOrderServiceImpl extends ServiceImpl<PiOrderMapper, PiOrder> implements IPiOrderService {
    public final Logger logger = LoggerFactory.getLogger(PiOrderServiceImpl.class);
    @Autowired
    private PiOrderMapper piOrderMapper;
    @Autowired
    private IPiOrderService iPiOrderService;
    @Autowired
    private IPiOrderItemService iPiOrderItemService;
    @Autowired
    private IPiCustomerService iPiCustomerService;
    @Autowired
    private IPiLinkmanService iPiLinkmanService;
    @Autowired
    private ITbUserService iTbUserService;
    @Autowired
    private IPiOrderLogService iPiOrderLogService;
    @Autowired
    private ITbUserService userService;
    @Autowired
    private IPiOrderItemMaterialService orderItemMaterialService;
    @Autowired
    private IPiMaterialService materialService;
    @Autowired
    private IPiOrderItemProcessService orderItemProcessService;
    @Autowired
    private IPiProcessService processService;
    @Autowired
    private IPiPayLogService iPiPayLogService;

    @Transactional
    @Override
    public boolean saveOrderAndItem(OrderAndItem orderAndItem) {
        PiOrder piOrder = orderAndItem.getPiOrder();
        piOrder.setIsDelete(1);//删除标识
        piOrder.setCreateDate(new Date());//更新日期
        piOrder.setCustomerName(iPiCustomerService.getById(piOrder.getCustomerId()).getName());//客户
        piOrder.setLinkmanName(iPiLinkmanService.getById(piOrder.getLinkmanId()).getName());//联系人
        piOrder.setLinkmanTel(iPiLinkmanService.getById(piOrder.getLinkmanId()).getTel());//电话号
        piOrder.setUpdateDate(new Date());//提交日期
        piOrder.setState(0);//默认状态
        piOrder.setUpdateUser(piOrder.getTbId());//创建人
        iPiOrderService.saveOrUpdate(orderAndItem.getPiOrder());//添加到订单表


        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("code", orderAndItem.getPiOrder().getCode());
        PiOrder piOrder1 = iPiOrderService.getOne(wrapper);
        for (PiOrderItem piOrderItem : orderAndItem.getPiOrderItems()) {//循环获取订单id
            piOrderItem.setOrderId(new Long(piOrder1.getId()));
            iPiOrderItemService.saveOrUpdate(piOrderItem);//添加到订单零件表
        }


        PiOrderLog piOrderLog = new PiOrderLog();
        piOrderLog.setOrderId(piOrder1.getId());
        piOrderLog.setTbId(piOrder.getTbId());
        piOrderLog.setUpdatetime(new Date());
        piOrderLog.setUserName(iTbUserService.getById(piOrder.getTbId()).getUserName());
        piOrderLog.setRemarks("添加/修改订单");
        iPiOrderLogService.saveOrUpdate(piOrderLog);//添加到订单记录表
        return false;
    }

    @Override
    public OrderExp find(Long id) {//订单的id
        //封装的一个实体类order，user，OrderItem，customer
        OrderExp orderExp = new OrderExp();
        //订单列表的数据
        PiOrder order = iPiOrderService.getById(id);
        //用户的数据
        TbUser user = userService.getById(order.getTbId());
        //客户的数据
        PiCustomer customer = iPiCustomerService.getById(order.getCustomerId());
        orderExp.setUser(user);
        orderExp.setCustomer(customer);
        orderExp.setOrder(order);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("orderId", id);
        //订单零件表
        List<PiOrderItem> piOrderItems = iPiOrderItemService.list(queryWrapper);
        //自己写的一个实体类，包括导出订单的for循环里面的数据
        List<OrderItem> orderItems = new ArrayList<>();
        for (PiOrderItem po : piOrderItems) {
            //循环零件表
            OrderItem orderItem = new OrderItem();
            //在orderitem添加在零件表里面的数据，循环添加
            //序号
            orderItem.setNo(po.getId());
            //零件图号
            orderItem.setCode(po.getCode());
            //零件名称
            orderItem.setName(po.getName());
            //材料
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("orderItemId", po.getId());
            //获取材料表中的数据
            List<PiOrderItemMaterial> materialList = orderItemMaterialService.list(wrapper);
            String mname = "";
            //材料费
            BigDecimal materialcost = new BigDecimal(0);
            //含税单价
            BigDecimal productprice = new BigDecimal(0);//11

            for (PiOrderItemMaterial pm : materialList) {
                PiMaterial material = materialService.getById(pm.getMaterialId());
                mname = mname + "," + material.getName();//材料名
                materialcost = materialcost.add(pm.getMaterCost());//材料费
            }

            //productprice=productprice.add(materialcost);//零件中加上材料费11
            //存入材料费
            orderItem.setMaterialcost(materialcost);
            /*if (name!=null){
                name=name.substring(1);
            }*/
            //存入材料的名称
            orderItem.setMaterialname(mname);

            List<PiOrderItemProcess> processList = orderItemProcessService.list(wrapper);
            String bcname = "";
            //工时
            double time = 0;
            //加工费
            BigDecimal workcost = new BigDecimal(0);
            //热处理
            BigDecimal heatcost = new BigDecimal(0);
            //表面处理
            BigDecimal surfacecost = new BigDecimal(0);
            for (PiOrderItemProcess pop : processList) {
                PiProcess process = processService.getById(pop.getProcessId());
                bcname += "," + process.getName();
                if (process.getCtype() == 2) {
                    surfacecost = surfacecost.add(pop.getPreCost()).add(pop.getProCost());
                }
                if (process.getCtype() == 3) {
                    heatcost = heatcost.add(pop.getPreCost()).add(pop.getProCost());
                }

                if (process.getCtype() == 1) {
                    workcost = workcost.add(pop.getProCost());
                }
                //准备工时
                time += pop.getPreWorkHour();
                //单间工时
                time += pop.getSgWorkHour();

                /*if(bcname!=null){
                    bcname=bcname.substring(1);
                }*/
            }
            orderItem.setBcnames(bcname);
            //数量
            orderItem.setTotal(po.getNum());
            orderItem.setWorkhour(time);
            orderItem.setWorkcost(workcost);
            orderItem.setHeatcost(heatcost);
            orderItem.setSurfacecost(surfacecost);

            //单价是加上这3种
            BigDecimal taxRate = new BigDecimal(0);
            taxRate = order.getTaxRate().divide(BigDecimal.valueOf(100)).add(BigDecimal.valueOf(1));


            productprice = productprice.add(workcost).add(heatcost).add(surfacecost).add(materialcost).multiply(taxRate);
            orderItem.setProductprice(productprice);
            /*orderItem.setProductprice(po.getPrice().add(po.getPrice().multiply(order.getTaxRate())));
            orderItem.setTotalprice(orderItem.getProductprice().multiply(new BigDecimal(po.getNum())));*/
            //总价是单价乘以数量
            orderItem.setTotalprice(productprice.multiply(new BigDecimal(po.getNum())));
            orderItems.add(orderItem);
        }
        orderExp.setOrderItemList(orderItems);
        return orderExp;
    }

    @Override
    public ResponseResult payAgin(PiOrder piOrder, long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        //请求
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


            alipayRequest.setBizContent("{\"out_trade_no\":\"" + piOrder.getCode() + "\","
                    + "\"total_amount\":\"" + piOrder.getPriceIt() + "\","
                    + "\"subject\":\"" + "订单零件" + "\","
                    + "\"body\":\"" + "订单零件购买支付" + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            result.setResult(alipayClient.pageExecute(alipayRequest).getBody());//支付宝统一首单下单页面接口，并返回form表单支付页


            /*
             * 添加支付记录
             * */
            logger.info("添加支付记录");
            PiPayLog piPayLog = new PiPayLog();
            piPayLog.setCreateTime(new Date());//支付日期
            piPayLog.setOutTradeNo(piOrder.getCode());//支付订单号
            piPayLog.setUserId(id);//操作人id
            piPayLog.setTotalAmount(piOrder.getPriceIt());//支付金额
            piPayLog.setPayType(0);//支付类型 0：支付宝   1：微信
            piPayLog.setTradeState(0);//支付状态 0：支付中  1：支付成功  2：支付失败
            iPiPayLogService.save(piPayLog);

            //添加订单记录
            PiOrderLog orderLog=new PiOrderLog();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",piOrder.getCode());
            PiOrder piOrder1 = iPiOrderService.getOne(queryWrapper);
            orderLog.setOrderId(piOrder1.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(piOrder1.getTbId());
            orderLog.setUserName(iPiCustomerService.getById(id).getName());
            orderLog.setRemarks("支付中···");
            iPiOrderLogService.saveOrUpdate(orderLog);//添加订单记录表
        } catch (AlipayApiException e) {
            e.printStackTrace();
            result.setMessage("支付失败" + e.toString());
            result.setSuccess(false);
            /*
             * 添加支付记录
             * */
            logger.info("添加支付记录");
            PiPayLog piPayLog = new PiPayLog();
            piPayLog.setCreateTime(new Date());//支付日期
            piPayLog.setOutTradeNo(piOrder.getCode());//支付订单号
            piPayLog.setUserId(id);//操作人id
            piPayLog.setPayType(0);//支付类型 0：支付宝   1：微信
            piPayLog.setTradeState(2);//支付状态 0：支付中  1：支付成功  2：支付失败
            iPiPayLogService.save(piPayLog);

            //添加订单记录
            PiOrderLog orderLog=new PiOrderLog();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",piOrder.getCode());
            PiOrder piOrder1 = iPiOrderService.getOne(queryWrapper);
            orderLog.setOrderId(piOrder1.getId());
            orderLog.setUpdatetime(new Date());
            orderLog.setTbId(piOrder1.getTbId());
            orderLog.setUserName(iPiCustomerService.getById(id).getName());
            orderLog.setRemarks("支付失败");
            iPiOrderLogService.saveOrUpdate(orderLog);//添加订单记录表
        }

        return result;
    }

    @Override
    public List getOrderPrice() {
        return piOrderMapper.getOrderPrice();
    }

    @Override
    public List<Map> getxiaoshoue() {

        return piOrderMapper.getxiaoshoue();
    }


}
